package a51qindian.com.comprehensive.activity;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.li.utils.ToastUtil;
import com.li.widget.MultipleLayout;
import com.li.widget.TopNavigationBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import a51qindian.com.comprehensive.Const;
import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.base.QDBaseActivity;
import a51qindian.com.comprehensive.city.CityVerifyAdapter;
import a51qindian.com.comprehensive.model.BaseModel;
import a51qindian.com.comprehensive.model.ShopVerifyInfo;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import a51qindian.com.comprehensive.net.SelectorObserver;
import a51qindian.com.comprehensive.util.SpUtil;
import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;


/**
 * Author: Li
 * Date: 2017/9/12 0012
 * Description: 店铺审核
 */

public class CityShopVerifyActivity extends QDBaseActivity {

    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.recycler_verify)
    RecyclerView mRecyclerVerify;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;
    @BindView(R.id.layout_refresh)
    SmartRefreshLayout mLayoutRefresh;

    private CityVerifyAdapter mVerifyAdapter;
    private List<ShopVerifyInfo> mShopVerifyInfoList;

    private static final String VERIFY_REFUSE = "2";
    private static final String VERIFY_PASS = "1";

    @Override
    protected void initSth() {
        super.initSth();
        setSmartRefreshLayout(mLayoutRefresh);
        mShopVerifyInfoList = new ArrayList<>();
        mTopNavigation.setNavigationBarListener(this);
        mRecyclerVerify.setLayoutManager(new LinearLayoutManager(CityShopVerifyActivity.this));
        mVerifyAdapter = new CityVerifyAdapter(CityShopVerifyActivity.this);
        mRecyclerVerify.setAdapter(mVerifyAdapter);
        showShopVerifyList(mUid,"0");
        mVerifyAdapter.setOnVerifyListener(new CityVerifyAdapter.OnVerifyListener() {
            @Override
            public void onRefuse(final int pos) {
                AlertDialog.Builder builder=new AlertDialog.Builder(CityShopVerifyActivity.this)
                        .setTitle("提示")
                        .setMessage("是否拒绝该商铺的审核")
                        .setNegativeButton("取消",null)
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                verifyShop(SpUtil.getUserInfo(CityShopVerifyActivity.this,SpUtil.USER_ID),
                                        mShopVerifyInfoList.get(pos).getShop_id(),
                                        VERIFY_REFUSE,pos);
                            }
                        });
                builder.create().show();
            }

            @Override
            public void onPass(final int pos) {
                AlertDialog.Builder builder=new AlertDialog.Builder(CityShopVerifyActivity.this)
                        .setTitle("提示")
                        .setMessage("是否通过该商铺的审核")
                        .setNegativeButton("取消",null)
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                verifyShop(SpUtil.getUserInfo(CityShopVerifyActivity.this,SpUtil.USER_ID),
                                        mShopVerifyInfoList.get(pos).getShop_id(),
                                        VERIFY_PASS,pos);
                            }
                        });
                builder.create().show();
            }
        });
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        super.onRefresh(refreshlayout);
        showShopVerifyList(mUid,"0");
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        super.onLoadmore(refreshlayout);
        showShopVerifyList(mUid,String.valueOf(mPage+1));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shop_verify;
    }

    /**
     * 显示商铺信息
     *
     * @param uid 用户编号
     */
    private void showShopVerifyList(String uid,String page) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("page",page);
        ObservableHelper.createObservable(RetrofitCreator.createService().shopVerifyList(map))
                .subscribe(new SelectorObserver<BaseModel<List<ShopVerifyInfo>>>() {
                    @Override
                    protected void onErrorCodeInfo(int code, String info) {
                        mLayoutContent.onSuccess();
                        stopRefreshLoad();
                        mLayoutRefresh.setLoadmoreFinished(true);
                        ToastUtil.showToast(CityShopVerifyActivity.this, info);
                    }

                    @Override
                    protected void onSuccess(BaseModel<List<ShopVerifyInfo>> listBaseModel) {
                        List<ShopVerifyInfo> shopVerifyInfoList = listBaseModel.getData();
                        mLayoutContent.onSuccess();
                        if (mIsRefresh) {
                            mPage=0;
                            mShopVerifyInfoList.clear();
                        }else {
                            mPage++;
                        }
                        stopRefreshLoad();
                        if (!mIsRefresh&&shopVerifyInfoList.size()< Const.DEFAULT_PAGE_SIZE) {
                            mLayoutRefresh.setLoadmoreFinished(true);
                        }
                        mShopVerifyInfoList.addAll(shopVerifyInfoList);
                        mVerifyAdapter.setShopVerifyInfoList(mShopVerifyInfoList);
                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopRefreshLoad();
                        mLayoutContent.onSuccess();
                        ToastUtil.showToast(CityShopVerifyActivity.this, e.getMessage());
                    }
                });

    }


    /**
     * 商铺审核
     *
     * @param uid    用户编号
     * @param shopId 商品编号
     * @param status 状态 1:通过，2：拒绝
     * @param pos    操作位置 用来更新界面
     */
    private void verifyShop(String uid, String shopId, final String status, final int pos) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("shop_id", shopId);
        map.put("status", status);
        Log.e("tag", "verifyShop: "+shopId);
        ObservableHelper.createObservable(RetrofitCreator.createService().shopVerify(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            int code = jsonObject.getInt("code");

                            mVerifyAdapter.notifyItemRemoved(pos);
                            if (code != 1) {
                                ToastUtil.showToast(CityShopVerifyActivity.this, jsonObject.getString("info"));
                                return;
                            }

                            if (status.equals(VERIFY_PASS)) {

                                ToastUtil.showToast(CityShopVerifyActivity.this, "该商铺已成功通过");
                            }else {
                                ToastUtil.showToast(CityShopVerifyActivity.this, "已拒绝该商铺");

                            }
                            mShopVerifyInfoList.remove(pos);
                            mVerifyAdapter.notifyItemRemoved(pos);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.e("tag", "onError: "+e.getMessage());
                        mLayoutContent.onSuccess();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


}
